package com.info.protocol.serial;

import com.info.protocol.enums.SerializeTypeEnum;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

@Slf4j
public class JdkSerializer implements Serializer {
    @Override
    public <T> byte[] serialize(T obj) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream os = new ObjectOutputStream(bos)) {

            os.writeObject(obj);
            return bos.toByteArray();

        } catch (IOException e) {
            e.printStackTrace();
            log.error("序列化 {} 对象出错", obj);
        }
        return new byte[0];
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> clz) {
        try (ByteArrayInputStream bin = new ByteArrayInputStream(data);
             ObjectInputStream oin = new ObjectInputStream(bin)) {

            return (T) oin.readObject();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("反序列化 对象出错");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            log.error("反序列化对象出错,未找到对应的类型 {}", e.getCause().getMessage());
        }
        return null;
    }

    @Override
    public byte getType() {
        return SerializeTypeEnum.JDK.getCode();
    }
}
